package main

import (
	"context"
	"log"
	"os"
	"time"
)

// todo https://studygolang.com/articles/10155?fr=sidebar
// goroutine 测试

var logg *log.Logger

func someHandler() {
	//ctx,cancel := context.WithCancel(context.Background())
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	//ctx,cancel := context.WithDeadline(context.Background(),time.Now().Add(5 * time.Second))

	go doTimeOutStuff(ctx)
	//go doStuff(ctx)
	//10秒后取消doStuff
	time.Sleep(10 * time.Second)
	cancel()
}
func doTimeOutStuff(ctx context.Context) {
	for {
		time.Sleep(1 * time.Second)
		if deadline, ok := ctx.Deadline(); ok {
			logg.Printf("deadline set")
			if time.Now().After(deadline) {
				//context deadline exceeded就是ctx超时的时候ctx.Err的错误消息。
				logg.Printf(ctx.Err().Error())
				return
			}
		}
		select {
		case <-ctx.Done():
			logg.Printf("done")
		default:
			logg.Printf("work")

		}
	}
}
func doStuff(ctx context.Context) {
	for {
		time.Sleep(1 * time.Second)
		select {
		case <-ctx.Done():
			logg.Printf("done")
			return
		default:
			logg.Printf("work")
		}
	}
}

func main() {

	logg = log.New(os.Stdout, "", log.Ltime)
	someHandler()
	logg.Printf("down")

}
